import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author jh.pei
 * @date 2024/10/17 11:23
 */
public class 合并k个已排序的链表 {
    public static void main(String[] args) {
        ListNode lList = ListNode.getLList(Arrays.asList(-1,0,0,0,1, 4, 5));
        ListNode rList = ListNode.getLList(Arrays.asList(0,2));
        ArrayList<ListNode> objects = new ArrayList<>();
        objects.addAll(Arrays.asList(lList, rList));
        ListNode listNode = mergeKLists(objects);
        ListNode.print(listNode)
        ;
    }



    public static ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        ListNode head = new ListNode(1000);
        int minvalue = 1000;
        ListNode current = head;
        while(lists != null && lists.size() > 0) {
            // 找到最小的节点
            for (ListNode list : lists) {
                if (list!= null && minvalue > list.val) {
                    minvalue = list.val;
                    current.next = list;
                }
            }
            // 删除最小的节点
            ArrayList<ListNode> nodes = new ArrayList<>();
            Boolean isAdd = false;
            for (ListNode listNode: lists) {
                if (listNode == null ) {
                    continue;
                }
                if (minvalue == listNode.val && !isAdd) {
                    listNode = listNode.next;
                    isAdd = true;
                    if(listNode != null) nodes.add(listNode);
                } else {
                    nodes.add(listNode);
                }
            }
            if (nodes.size() == 0) {
                break;
            }
            lists = nodes;
            // 游标往右移动
            current = current.next;
            minvalue = 1000;

        }
        return head.next;
    }


}
